import { createRouter, createWebHistory } from 'vue-router'
import { useUsersStore } from '../stores'
// import { storage } from '../utils'
import NProgress from 'nprogress'
import HomeRoutes from './HomeRoutes'
import WorkbenchRoutes from './WorkbenchRoutes'
import 'nprogress/nprogress.css'
import config from '../config'



NProgress.configure({ showSpinner: false })

const routes = [
  {
    name: '',
    path: '',
    redirect: { name: 'Home' },
  },
  {
    name: 'Login',
    path: '/login',
    meta: {
      title: 'Login'
    },
    component: () => import('../views/Login.vue'),
  },
  {
    name: 'QuickNavigation',
    path: '/quick-navigation',
    meta: {
      title: 'QuickNavigation'
    },
    component: () => import('../views/QuickNavigation.vue'),
    // redirect: { name: 'Workbench' },
    // children: [
    //   {
    //     name: 'Workbench',
    //     path: 'workbench',
    //     meta: {
    //       title: 'Workbench'
    //     },
    //     component: () => import('../views/Workbench.vue'),
    //   },
    //   {
    //     name: 'ApplicationCrib',
    //     path: 'applicationCrib',
    //     meta: {
    //       title: 'ApplicationCrib'
    //     },
    //     component: () => import('../views/ApplicationCrib.vue'),
    //   },
    // ]
  },
  WorkbenchRoutes,
  HomeRoutes,
  {
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
  },
]

// 使用 createWebHistory 创建一个基于 HTML5 History API 的路由历史记录
const router = createRouter({
  // 创建一个路由历史记录对象
  history: createWebHistory(),
  // 定义路由配置
  routes,
  // 启用严格模式，确保路由的唯一性和正确性
  strict: true,
  // 定义滚动行为，每次导航时滚动到页面顶部
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// const openUrls: any = []
// 定义一个路由守卫，在每次路由跳转前执行
router.beforeEach((to, _, next) => {
  // 开启进度条
  NProgress.start()
  // 获取用户仓库实例
  const usersStore = useUsersStore()
  // 获取用户仓库中的所有状态
  const user = usersStore.getAllState()
  // document.title = to.meta.title ? to.meta.title + '' + config.site.title : config.site.title
  document.title = config.site.title
  // 如果目标路由是 Test，则直接放行
  if (to.name === 'Test' || to.name === 'Workbench' || to.name === 'ApplicationCrib') {
    next()
  } else {
    // 如果目标路由不是 Login 且用户没有 token，则跳转到 Login 页面
    if (to.name !== 'Login' && !user.token) {
      console.log('router.beforeEach', user)
      // 关闭进度条
      NProgress.done()
      // storage.clear()
      // 跳转到 Login 页面
      next({ name: 'Login' })
    } else {
      // 否则，放行
      next()
    }
  }
})


router.afterEach(() => {
  NProgress.done()
})

export default router